'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 购买挑战次数
 * @author agl
 */

var _ = require('lodash');
var async = require('async');
var moment = require('moment');
var Code = require('../../../../consts/code');
var moduleType = require('../../../../consts/moduleType');
var operationType = require('../../../../consts/operationType');
var configUtil = require('../../../../util/configUtil');
var constantUtil = require('../../../../util/constantUtil');
var PlayerManager = require('../../../../libs/playerManager');
var taskService = require('../../../../services/taskService');
var roleService = require('../../../../services/roleService');
var rewardService = require('../../../../services/rewardService');
var dataApi = require('../../../../libs/dataApi.js');
var vipConf = require('../../../../config/vipConf.js');
var expeditionConf = require('../../../../config/expeditionConf.js');

module.exports = function (msg, session, next) {
    var role_id = session.uid;

    var player_manager = new PlayerManager(role_id);
    var reward_list;
    async.waterfall(
        [
            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(['expedition', 'role', 'build', 'soldier', 'accrued'], cb);
            },
            function (cb) {
                var expedition_model = player_manager.expedition;
                var role_model = player_manager.role;
                var monster_open_lvl = constantUtil.value('monster_open_lvl');
                if (role_model.lv < monster_open_lvl) {
                    return next(null, {
                        code: Code.USER_LEVEL_NOT_ENOUGH
                    });
                }

                if (!expedition_model.box_id || expedition_model.box_id != expedition_model.pass_id) {
                    return next(null, {
                        code: Code.EXPEDITION_NO_BOX
                    });
                }

                reward_list = expeditionConf.getBoxReward(expedition_model.box_id);
                rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_EXPEDITION, operationType.OPR_EXPEDITION_SHOP_BUY);
                expedition_model.box_id = 0;

                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }

            return next(null, {
                code: Code.OK,
                result: {}
            });
        }
    );
};
